import React, { useState, useEffect, useCallback } from 'react';
import './FileTransferManager.css';

interface TransferTask {
  id: string;
  fileName: string;
  deviceId: string;
  sourcePath: string;
  targetPath: string;
  progress: number;
  status: 'pending' | 'transferring' | 'paused' | 'completed' | 'error';
  speed: number;
  error?: string;
}

interface FileTransferManagerProps {
  onClose?: () => void;
}

export const FileTransferManager: React.FC<FileTransferManagerProps> = ({ onClose }) => {
  const [tasks, setTasks] = useState<TransferTask[]>([]);
  const [isMinimized, setIsMinimized] = useState(false);

  const addTask = useCallback((task: Omit<TransferTask, 'id' | 'progress' | 'status' | 'speed'>) => {
    const newTask: TransferTask = {
      ...task,
      id: Date.now().toString(),
      progress: 0,
      status: 'pending',
      speed: 0
    };
    setTasks(prev => [...prev, newTask]);
    return newTask.id;
  }, []);

  const updateTaskProgress = useCallback((taskId: string, progress: number, speed: number) => {
    setTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { 
            ...task, 
            progress, 
            speed,
            status: progress === 100 ? 'completed' : 'transferring'
          }
        : task
    ));
  }, []);

  const toggleTaskStatus = useCallback((taskId: string) => {
    setTasks(prev => prev.map(task => 
      task.id === taskId 
        ? { 
            ...task, 
            status: task.status === 'transferring' ? 'paused' : 'transferring'
          }
        : task
    ));
  }, []);

  const removeTask = useCallback((taskId: string) => {
    setTasks(prev => prev.filter(task => task.id !== taskId));
  }, []);

  const startFileTransfer = useCallback(async (task: TransferTask) => {
    try {
      await window.electronAPI.sendFileToDevice(
        task.deviceId,
        task.sourcePath,
        task.targetPath
      );
    } catch (error: any) {
      setTasks(prev => prev.map(t => 
        t.id === task.id 
          ? { ...t, status: 'error', error: error.message }
          : t
      ));
    }
  }, []);

  return (
    <div className={`file-transfer-manager ${isMinimized ? 'minimized' : ''}`}>
      <div className="transfer-header">
        <h3>文件传输</h3>
        <div className="header-controls">
          <button onClick={() => setIsMinimized(!isMinimized)}>
            {isMinimized ? '展开' : '最小化'}
          </button>
          <button onClick={onClose}>关闭</button>
        </div>
      </div>
      
      <div className="transfer-list">
        {tasks.map(task => (
          <div key={task.id} className={`transfer-item ${task.status}`}>
            <div className="task-info">
              <div className="file-name">{task.fileName}</div>
              <div className="task-details">
                <span className="status">{getStatusText(task.status)}</span>
                <span className="speed">{formatSpeed(task.speed)}</span>
              </div>
            </div>
            
            <div className="progress-bar">
              <div 
                className="progress-fill"
                style={{ width: `${task.progress}%` }}
              />
              <span className="progress-text">{task.progress}%</span>
            </div>
            
            <div className="task-controls">
              {task.status !== 'completed' && task.status !== 'error' && (
                <button
                  onClick={() => toggleTaskStatus(task.id)}
                  className="control-button"
                >
                  {task.status === 'transferring' ? '暂停' : '继续'}
                </button>
              )}
              <button
                onClick={() => removeTask(task.id)}
                className="control-button remove"
              >
                移除
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

function getStatusText(status: TransferTask['status']): string {
  const statusMap = {
    pending: '等待中',
    transferring: '传输中',
    paused: '已暂停',
    completed: '已完成',
    error: '传输失败'
  };
  return statusMap[status];
}

function formatSpeed(bytesPerSecond: number): string {
  if (bytesPerSecond === 0) return '';
  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
  let size = bytesPerSecond;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`;
} 